package factory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SimpleContainer {
    private static Map<Class<?>,Object> map = new HashMap<Class<?>, Object>();

    public static <T> T getBean(Class<T> Beanclazz) {
        return (T) map.get(Beanclazz);
    }

    public static void addBean(Class<?> beanClass){
        try {
            Constructor<?> constructor = beanClass.getConstructor();
            Object o = constructor.newInstance();
            map.put(beanClass,o);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void injectDepend(Object bean){
        Class<?> aClass = bean.getClass();
        Field[] fields = aClass.getFields();
        for (Field field : fields) {
            if(field.isAnnotationPresent(Autowired.class)){
                Class<?> type = field.getType();
                Object o = getBean(type);
                try {
                    field.set(bean,o);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
